<template>
    <div class="app-container">
        <!-- 表格-条件筛区域  -->
        <div class="filter-container">
            <el-input placeholder="请输入名称" v-model="searchParam.SEARCH_LIKE_role_name" style="width: 200px;" class="filter-item" @keyup.enter.native="handleFilter"/>
            <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter"> 筛选 </el-button>
            <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate"> 新增 </el-button>
        </div>

        <!-- 表格-内容区域 -->
        <el-table v-loading="listLoading" :key="tableKey" :data="tableList" border fit highlight-current-row   style="width: 100%;" >
            <el-table-column label="角色名称" min-width="60px"  align="left" >
                <template slot-scope="scope">
                    <span class="link-type" @click="handleUpdate(scope.row)">{{ scope.row.roleName }}</span>
                </template>
            </el-table-column>
            <el-table-column label="角色编码" min-width="60px" align="left" >
                <template slot-scope="scope">
                    <span>{{ scope.row.roleCode }}</span>
                </template>
            </el-table-column>
            <el-table-column label="角色描述" min-width="100px" align="left" >
                <template slot-scope="scope">
                    <span>{{ scope.row.remark }}</span>
                </template>
            </el-table-column> 
            <el-table-column label="操作" align="center" width="240" class-name="small-padding">
                <template slot-scope="scope">
                    <el-button type="text"  icon="el-icon-edit" class="el-button--primary"  @click="handleUpdate(scope.row)"> 编辑 </el-button>
                    <el-button type="text"  icon="el-icon-delete"   class="el-button--danger"  @click="handleDelete(scope.row)"> 删除 </el-button>
                    <!-- <el-button type="danger"    @click="handlePermission(scope.row)"> 设置权限</el-button> -->
                </template>
            </el-table-column>
        </el-table>

        <!-- 表格-页脚区域 -->
        <pagination v-show="tableTotal>0" :total="tableTotal" :page.sync="pageRequest.pageNum" :limit.sync="pageRequest.pageSize" @pagination="getList" />

        <!--新增编辑界面-->
        <el-dialog :title="operation?'新增':'编辑'" width="60%" top ="5vh" :visible.sync="dialogFormVisible" :close-on-click-modal="false">
            <div  style="height:500px;overflow-y: scroll;" >
                <el-form :model="dataForm" label-width="100px" :rules="dataFormRules" ref="dataForm"  style="width:98%">
                    <el-form-item label="角色名称" prop="roleName">
                        <el-input size="mini" v-model="dataForm.roleName" auto-complete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="角色编码" prop="roleCode">
                        <el-input size="mini" v-model="dataForm.roleCode" auto-complete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="角色描述" prop="remark">
                        <el-input size="mini" v-model="dataForm.remark" auto-complete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="权限配置" prop="remark">

                        <!-- <el-tree  size="mini"  style="margin-top:10px"  :data="data" show-checkbox   node-key="id" ref="tree" :props="defaultProps">
                        </el-tree> -->
                        

                        <tree-table :data="data" :columns="columns" :listLoading="listLoading2"
                            :expand-all="true"   border ref="menuTree">
<!--                            <el-table-column label="数据权限"   align="left"  >-->
<!--                                <template slot-scope="scope">-->
<!--                                    <el-radio-group v-if="scope.row.type==1 && scope.row.isChecked " v-model="scope.row.dataPerm">-->
<!--                                        <el-radio  :label="0"  >所有(默认)</el-radio>-->
<!--                                        <el-radio  :label="1"  >本机构</el-radio>-->
<!--                                        <el-radio  :label="2"  >本部门</el-radio>-->
<!--                                        &lt;!&ndash; <el-radio  :label="3"  >自定义</el-radio> &ndash;&gt;-->
<!--                                    </el-radio-group>-->
<!--                                    &lt;!&ndash; <el-select    v-if="scope.row.dataPerm==3"-->
<!--                                        placeholder="请选择机构部门"  style="width: 200px;margin-left:20px" ref="selectReport">-->
<!--                                        <el-option :value="scope.row.dataPerm" label="AAA"-->
<!--                                            style="width: 200px;height:200px;overflow: auto;background-color:#fff">-->
<!--                                            <el-tree :data="organData"     :props="organTreeProps"  show-checkbox   ></el-tree>-->
<!--                                        </el-option>-->
<!--                                    </el-select> &ndash;&gt;-->
<!--                                </template>-->
<!--                            </el-table-column>-->
                        </tree-table>



                    </el-form-item>
                </el-form>
            </div>
            <div slot="footer" class="dialog-footer">
                <el-button size="mini" @click.native="closeDialog()"  >取消</el-button>
                <el-button size="mini" @click.native="saveFormData()" :loading="editLoading"   type="primary"  >提交</el-button>
            </div>
        </el-dialog>
        
        <Drawer  :drawerVisible.sync="drawerVisible"  title="编辑权限"   direction="right" :mask="true"  @close="close" >
            
            <div style="height:100px">
                <el-form :model="dataForm" label-width="100px" :rules="dataFormRules" ref="dataForm">
                    <el-form-item label="角色名称" prop="roleName">
                        <el-input size="mini" v-model="dataForm.roleName" auto-complete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="角色编码" prop="roleCode">
                        <el-input size="mini" v-model="dataForm.roleCode" auto-complete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="角色描述" prop="remark">
                        <el-input size="mini" v-model="dataForm.remark" auto-complete="off"></el-input>
                    </el-form-item>
                    <el-form-item label="权限配置" prop="remark" style="max-height:500px;overflow-y: scroll;"  >
                        <el-tree  size="mini"  style="margin-top:10px"  :data="data" show-checkbox default-expand-all node-key="id" ref="tree" :props="defaultProps">
                        </el-tree>
                    </el-form-item>
                </el-form>
            </div>
            <div slot="footer"  class="dialog-footer" style="float:right;margin-right:20px">
                <el-button size="mini" @click.native="closeDialog()"  >取消</el-button>
                <el-button size="mini" @click.native="saveFormData()" :loading="editLoading"   type="primary"  >提交</el-button>
            </div>


        </Drawer>
        

    </div>
</template>

<script>

import waves from '@/directive/waves' // Waves directive
import treeTable from '@/components/TreeTable4Role'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination
import Drawer from '@/components/Drawer' // 
export default {
  name: 'system-role',
  directives: { waves , },
  components: { Pagination ,Drawer , treeTable },
  filters: { },
  data() {
        return {
            tableKey: 0,
            tableList: [],//表格数据源
            tableTotal: 0,//表格总条数数据
            listLoading: true,
            listLoading2: false,
            pageRequest: {  pageNum: 1, pageSize: 10, },
            searchParam:{SEARCH_LIKE_rolename:''},
            //默认不显示弹出框
            dialogFormVisible: false,
            operation: true, // true:新增, false:编辑
            editLoading: false,//保存表单时loading框
            data: [],//角色权限---树形结构渲染
            //树形结构---默认属性值设置
            defaultProps: {
                children: 'children',
                label: 'name'
            },

            organTreeProps:{
                children: 'children',
                label: 'deptName'
            },

            // 新增编辑界面数据
            dataForm: {},
            initDataForm: { roleName: '', roleCode: '', remark: '', },
            //表单检验规则
            dataFormRules: {
                roleName: [ { required: true, message: '请输入角色名', trigger: 'blur' } ],
                roleCode: [ { required: true, message: '请输入角色编码', trigger: 'blur' } ]
            },

            columns: [
                // { text: 'ID', value: 'id',  width: '300px',align:'center' },
                { text: '资源名称', value: 'name', align: 'left',   },
                { text: '资源类型', value: 'type', align: 'center', tagFlag: true,  
                    tagFormatter: [
                        { text: '导航目录', value: 0, type: '' },
                        { text: '跳转菜单', value: 1, type: 'success' },
                        { text: '页面按钮', value: 2, type: 'danger' }
                    ]
                },
            ],

            // 获取机构树信息---
            organData : [] ,
      
            //抽屉相关
            drawerVisible: false,


        }
  },
  created() {
        this.getList();
        this.getMenuData();
        // this.getOrganList();
  },
    methods: {

        // // 获取机构树信息---
        // getOrganList: function() {
        //     // 【API请求】----获取菜单树列表
        //     this.$api.getOrganList().then((res) => {
        //         this.organData = res.data
        //     }).catch((res) => {
        //         this.$message({ message: '机构数据获取失败', type: 'error' })
        //     })
        // },

        close(){
            this.drawerVisible = false;
        },
        //设置权限--抽屉
        handlePermission(row){
            this.drawerVisible = true;
        },

        //获取菜单树信息---
        getMenuData:function(){
            //【API请求】----获取菜单树列表
            this.$api.getMenuTreeList().then((res) => {
                // this.data = res.data

                // 重新赋值 菜单资源的树形状态 
                let iteration = function(arr) {
                    let newArr = [];
                    if (arr != undefined && arr.length > 0) {
                        newArr = arr.map(item => {
                            item.dataPerm = 0;
                            if (item.children != undefined && item.children.length > 0) {
                                iteration(item.children);
                            }
                            return item;
                        });
                    }
                    return newArr;
                };
                this.data   = iteration( res.data );



            }).catch((res) => {
                alert(1)
            })
        },
        //获取表格数据
        getList() {
            this.listLoading = true
            //【API请求】----获取角色列表数据
            this.$api.getRoleList(this.pageRequest).then(response => {
                this.tableList = response.data.content
                this.tableTotal = response.data.total
                this.listLoading = false;
            })
        },
        //表格数据筛选
        handleFilter() {
            this.pageRequest = {
                pageNum: 1,
                pageSize: 10,
            }
            this.pageRequest.searchParam = this.searchParam
            this.getList()
        },
        
        //【按钮点击】--- 弹出新增表单
        handleCreate() {
            this.operation = true;
            this.dataForm = this.initDataForm;
            this.dialogFormVisible = true
            this.$nextTick(() => {
                this.$refs['dataForm'].clearValidate()
                this.$refs.menuTree.showCheckedStatus( [] );
                // this.$refs.tree.setCheckedKeys([]);
                this.editLoading = false;
            })
        },
        //【按钮点击】--- 弹出编辑表单
        handleUpdate(row) {
            this.operation = false; 
            this.dataForm = Object.assign({}, row)
            this.dialogFormVisible = true;
            this.$nextTick(() => {
                this.$refs['dataForm'].clearValidate()
                this.editLoading = false;
                // this.$refs.tree.setCheckedKeys([]);
                //【API请求】--- 获取角色信息绑定的菜单资源
                this.$api.getRoleCheckedIds2({roleId:row.id}).then(response => {
                    
                    this.$refs.menuTree.showCheckedStatus(  response.data  );

                    // setTimeout(() => {
                    //     response.data.forEach(value  => {
                    //         this.$refs.tree.setChecked ( value , true , false   );
                    //     });
                    // }, 100);

                })
            })

        },
        //保存表单数据
        saveFormData() {
            

            this.$refs['dataForm'].validate((valid) => {
                if (!valid) {
                    return false;
                }
                this.editLoading = true;
                
                //-------------------树形结构数据Start--------------------
                // let submitEntity   = this.dataForm ; 
                // let roleMenus0 = this.$refs.tree.getCheckedKeys();
                // let roleMenus1 = this.$refs.tree.getHalfCheckedKeys();
                // let roleMenus = roleMenus0.concat(roleMenus1);
                // submitEntity.menuIds = JSON.stringify(roleMenus);
                //-------------------树形结构数据end --------------------

                //-------------------树形表格结构数据 Start--------------------
                let submitEntity   = this.dataForm ; 
                let treeData = this.$refs.menuTree.data;
                let selectedData = this.translateTreeToData ( treeData )
                submitEntity.dataPermStr = JSON.stringify(selectedData);
                //-------------------树形表格结构数据 End --------------------

                //【API请求】----保存角色数据
                this.$api.saveRoleInfo( submitEntity ).then(() => {
                    this.editLoading = false;//关闭loading框
                    this.dialogFormVisible = false;//关闭表单页面
                    this.drawerVisible = false;
                    this.$refs['dataForm'].resetFields();//重置表单数据
                    this.getList();//重新获取表格数据
                    this.$notify({ title: '成功',  message: '保存成功', type: 'success', duration: 2000 })
                })
            })
        },

        translateTreeToData(list) {
            let data = JSON.parse(JSON.stringify(list))
            const result = []
            data.forEach((item) => {
                const loop = (data) => {
                    const child = data.children
                    if (child) {
                        for (let i = 0; i < child.length; i++) {
                            loop(child[i])
                        }
                        delete data.children
                    }
                    // 只获取选中状态的
                    if(data.isChecked  ){
                        result.push({id:data.id , name:data.name  , code:data.code ,   dataPerm : data.dataPerm    })
                        // result.push(data)
                    }
                }
                loop(item)
            })
            return result
        } ,

        //【按钮点击】---删除行
        handleDelete(row) {
            this.$confirm('确认删除该记录吗？', '提示', {}).then(() => {
                //【API请求】---- 删除角色数据  
                this.$api.deleteRole({ids:row.id}).then(() => {
                    this.$message({  message: '操作成功', type: 'success' })
                    this.pageRequest.pageNum = 1
                    this.getList();
                })
            }).catch(() => {
            });
        },
        //关闭表单弹出框
        closeDialog(){
            this.$refs['dataForm'].resetFields();
            this.dialogFormVisible = false;
            this.drawerVisible = false;
        }
     
     
     
  }
}
</script>
